package com.zzyl.nursing.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * TODO
 *
 * @Author katana
 * @Date 2025/5/23 16:21
 */
@Service
public class WechatServiceImpl  implements WechatService {
    
    //小程序ID
    @Value("${wechat.appId}")
    private String appId;
    
    //小程序密钥
    @Value("${wechat.appSecret}")
    private String appSecret;
    
    //获取手机号API地址
    private static final String POST_PHONE_API_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";
    
    //小程序登录API地址
    private static final String GET_OPEN_ID_URL = "https://api.weixin.qq.com/sns/jscode2session";
    
    //获取访问Token的API地址
    private static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";
    
    
    /**
     * 获取小程序基本参数
     * @return
     */
    public Map<String, Object> getAppConfig(){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("appid",appId);
        paramMap.put("secret",appSecret);
        return paramMap;
    }
    
    //获取小程序访问getAccessToken
    private String getAccessToken() {
        //1 组装参数
        Map<String,Object> params = getAppConfig();
        params.put("grant_type","client_credential");
        //2 发送请求
        String rseult = HttpUtil.get(GET_ACCESS_TOKEN_URL, params);
        
        if (StringUtils.isEmpty(rseult)){
            throw new RuntimeException("获取小程序访问token失败");
        }
        JSONObject jsonObject = JSON.parseObject(rseult);
        return jsonObject.getString("access_token");
    }
    /**
     * 根据临时凭证码（openId获取专用凭证码）获取openId
     *
     * @param code
     * @return
     */
    @Override
    public String getOpenId(String code) {
        //1 组装参数
        Map<String, Object> paramMap = this.getAppConfig();
        paramMap.put("grant_type","authorization_code");//授权类型
        paramMap.put("js_code", code);
        
        //2 发送请求
        String result = HttpUtil.get(GET_OPEN_ID_URL, paramMap);
        if(StringUtils.isBlank(result)) {
            throw new BaseException("获取OpenId失败");
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        
        if(!jsonObject.containsKey("openid")) {
            throw new BaseException("获取OpenId失败");
        }
        return jsonObject.getString("openid");
    }
    
    /**
     * 根据临时凭证码（phoneCode获取专用凭证码）获取手机号
     *
     * @param phoneCode
     * @return
     */
    @Override
    public String getPhone(String phoneCode) {
        
        //1 获取访问Token
        String  accessToken = this.getAccessToken();
        String url = POST_PHONE_API_URL + accessToken;
        
        //2 组装参数
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("code",phoneCode);
        
        //3 发送请求
        String result = HttpUtil.post(url, JSON.toJSONString(paramMap));
        if(StringUtils.isBlank(result)) {
            throw new BaseException("调用微信获取手机号接口失败");
        }
        
        //3. 解析响应结果，得到phoneNumber手机号
        JSONObject jsonObject = JSON.parseObject(result);
        
        Integer errcode = jsonObject.getInteger("errcode");
        if(errcode!=null && errcode!=0) {
            throw new BaseException("调用微信获取手机号接口失败,错误信息为:" + errcode);
        }
        
        String phoneInfo = jsonObject.getString("phone_info");
        JSONObject phoneInfoObject = JSON.parseObject(phoneInfo);
        return phoneInfoObject.getString("phoneNumber");
    }
    
}
